package org.gdstash.ui.character;

import org.gdstash.character.GDChar;
import org.gdstash.ui.GDHelpActionListener;
import org.gdstash.ui.GDLogoDialog;
import org.gdstash.ui.GDStashFrame;
import org.gdstash.ui.util.AdjustablePanel;
import org.gdstash.ui.util.GDCharInfoList;
import org.gdstash.util.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

public class GDCharEditPane extends AdjustablePanel {
    private GDStashFrame frame;
    private GDCharEditTabbedPane tabEdit;
    private JButton btnReload;
    private JButton btnHelp;
    private JComboBox<String> cbSelChar;
    private JButton btnFileSave;
    private JPanel pnlMain;
    private GDCharInfoList.GDCharFileInfo info;

    public GDCharEditPane(final GDStashFrame frame) {
        this.frame = frame;
        this.adjustUI();
        this.setChar(null);
        GroupLayout layout = null;
        GroupLayout.SequentialGroup hGroup = null;
        GroupLayout.SequentialGroup vGroup = null;
        this.pnlMain = this.buildMainPanel();
        final JScrollPane scroll = new JScrollPane(this.pnlMain);
        scroll.getVerticalScrollBar().setUnitIncrement(2 * GDStashFrame.iniConfig.sectUI.fontSize);
        layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup().addComponent(scroll));
        layout.setHorizontalGroup(hGroup);
        vGroup = layout.createSequentialGroup();
        vGroup.addGroup(layout.createParallelGroup().addComponent(scroll));
        layout.setVerticalGroup(vGroup);
    }

    @Override
    public void adjustUI() {
        Font fntLabel = UIManager.getDefaults().getFont("Label.font");
        Font fntButton = UIManager.getDefaults().getFont("Button.font");
        if (fntButton == null) {
            fntButton = fntLabel;
        }
        Font fntCombo = UIManager.getDefaults().getFont("ComboBox.font");
        if (fntCombo == null) {
            fntCombo = fntLabel;
        }
        fntLabel = fntLabel.deriveFont((float) GDStashFrame.iniConfig.sectUI.fontSize);
        fntButton = fntButton.deriveFont((float) GDStashFrame.iniConfig.sectUI.fontSize);
        fntCombo = fntCombo.deriveFont((float) GDStashFrame.iniConfig.sectUI.fontSize);
        GDCharInfoList.adjustCharInfos(null, null);
        if (this.tabEdit == null) {
            this.tabEdit = new GDCharEditTabbedPane();
        } else {
            this.tabEdit.adjustUI();
        }
        if (this.btnReload == null) {
            (this.btnReload = new JButton()).addActionListener(new ReloadActionListener());
        }
        this.btnReload.setText(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "BTN_RELOAD"));
        this.btnReload.setIcon(GDImagePool.iconBtnReload24);
        this.btnReload.setFont(fntButton);
        GDStashFrame.setMnemonic(this.btnReload, "MNC_RELOAD");
        if (this.btnHelp == null) {
            (this.btnHelp = new JButton()).addActionListener(new GDHelpActionListener("07_charedit.html"));
        }
        this.btnHelp.setText(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "BTN_HELP"));
        this.btnHelp.setIcon(GDImagePool.iconBtnQuestion24);
        this.btnHelp.setFont(fntButton);
        GDStashFrame.setMnemonic(this.btnHelp, "MNC_HELP");
        if (this.cbSelChar == null) {
            (this.cbSelChar = new JComboBox<String>()).addActionListener(new CharSelectActionListener());
        }
        final int idx = this.cbSelChar.getSelectedIndex();
        this.cbSelChar.removeAllItems();
        final String[] entries = GDCharInfoList.getCharInfos();
        for (int i = 0; i < entries.length; ++i) {
            this.cbSelChar.addItem(entries[i]);
        }
        if (idx != -1) {
            this.cbSelChar.setSelectedIndex(idx);
        }
        this.cbSelChar.setFont(fntCombo);
        this.cbSelChar.setMaximumSize(new Dimension(1000, 3 * GDStashFrame.iniConfig.sectUI.fontSize));
        if (this.btnFileSave == null) {
            (this.btnFileSave = new JButton()).addActionListener(new FileSaveActionListener());
        }
        this.btnFileSave.setText(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "BTN_CHAR_SAVE"));
        this.btnFileSave.setIcon(GDImagePool.iconBtnSave24);
        this.btnFileSave.setFont(fntButton);
        GDStashFrame.setMnemonic(this.btnFileSave, "MNC_CHAR_SAVE");
    }

    public void refresh() {
        this.refreshCharSelection();
    }

    private JPanel buildMainPanel() {
        final JPanel panel = new JPanel();
        final JPanel pnlCharSel = this.buildCharSelPanel();
        GroupLayout layout = null;
        GroupLayout.SequentialGroup hGroup = null;
        GroupLayout.SequentialGroup vGroup = null;
        layout = new GroupLayout(panel);
        panel.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup().addComponent(pnlCharSel).addComponent(this.tabEdit));
        layout.setHorizontalGroup(hGroup);
        vGroup = layout.createSequentialGroup();
        vGroup.addGroup(layout.createParallelGroup().addComponent(pnlCharSel)).addGroup(layout.createParallelGroup().addComponent(this.tabEdit));
        layout.setVerticalGroup(vGroup);
        layout.linkSize(0, pnlCharSel, this.tabEdit);
        return panel;
    }

    private JPanel buildCharSelPanel() {
        final JPanel panel = new JPanel();
        final JPanel pnlButtonFile = this.buildFileButtonPanel();
        GroupLayout layout = null;
        GroupLayout.SequentialGroup hGroup = null;
        GroupLayout.SequentialGroup vGroup = null;
        layout = new GroupLayout(panel);
        panel.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup().addComponent(pnlButtonFile).addComponent(this.cbSelChar));
        layout.setHorizontalGroup(hGroup);
        vGroup = layout.createSequentialGroup();
        vGroup.addGroup(layout.createParallelGroup().addComponent(pnlButtonFile)).addGroup(layout.createParallelGroup().addComponent(this.cbSelChar));
        layout.setVerticalGroup(vGroup);
        layout.linkSize(0, pnlButtonFile, this.cbSelChar);
        layout.linkSize(1, pnlButtonFile, this.cbSelChar);
        return panel;
    }

    private JPanel buildFileButtonPanel() {
        final BorderLayout layout = new BorderLayout();
        final JPanel panel = new JPanel();
        panel.setLayout(layout);
        panel.add(this.btnFileSave, "Center");
        panel.add(this.btnReload, "West");
        panel.add(this.btnHelp, "East");
        int size = 12;
        if (GDStashFrame.iniConfig != null) {
            size = GDStashFrame.iniConfig.sectUI.fontSize;
        }
        final Dimension dimMax = new Dimension(50 * size, 2 * size);
        panel.setPreferredSize(dimMax);
        panel.setMaximumSize(dimMax);
        return panel;
    }

    public void initCharSelection() {
        this.cbSelChar.removeAllItems();
        this.cbSelChar.addItem("");
        for (final GDCharInfoList.GDCharFileInfo info : GDCharInfoList.gdCharFileInfos) {
            this.cbSelChar.addItem(info.charInfo);
        }
    }

    public void updateConfig() {
        if (this.tabEdit != null) {
            this.tabEdit.updateConfig();
        }
    }

    public void refreshCharSelection() {
        File file = null;
        if (this.info != null) {
            file = this.info.charFile;
        }
        this.cbSelChar.removeAllItems();
        this.cbSelChar.addItem("");
        GDCharInfoList.GDCharFileInfo selInfo = null;
        int idx = -1;
        int i = 1;
        for (final GDCharInfoList.GDCharFileInfo info : GDCharInfoList.gdCharFileInfos) {
            this.cbSelChar.addItem(info.charInfo);
            if (info.charFile.equals(file)) {
                selInfo = info;
                idx = i;
            }
            ++i;
        }
        if (idx == -1) {
            this.setChar(null);
        } else {
            this.cbSelChar.setSelectedIndex(idx);
        }
    }

    public void refreshCharInfo(final GDCharInfoList.GDCharFileInfo info) {
        if (info == null) {
            return;
        }
        if (this.info == null) {
            return;
        }
        if (this.info.fileName.equals(info.fileName)) {
            this.setChar(this.info = info);
        }
    }

    public void setChar(final GDCharInfoList.GDCharFileInfo info) {
        this.info = info;
        if (info == null) {
            this.tabEdit.setChar(null);
        } else {
            this.tabEdit.setChar(info.gdChar);
        }
    }

    public void updateChar() {
        if (this.info == null) {
            return;
        }
        if (this.info.gdChar == null) {
            return;
        }
        this.tabEdit.updateChar(this.info.gdChar);
    }

    private class ReloadActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            GDCharInfoList.findChars(GDCharEditPane.this.frame, GDCharEditPane.this.info);
            if (GDCharEditPane.this.info != null) {
                for (final GDCharInfoList.GDCharFileInfo ci : GDCharInfoList.gdCharFileInfos) {
                    if (ci.fileName.equals(GDCharEditPane.this.info.fileName)) {
                        GDCharEditPane.this.info = ci;
                        break;
                    }
                }
            }
            if (GDCharEditPane.this.frame.pnlCharInventory != null) {
                GDCharEditPane.this.frame.pnlCharInventory.refreshCharInfo(GDCharEditPane.this.info);
            }
            if (GDCharEditPane.this.frame.pnlCharEdit != null) {
                GDCharEditPane.this.frame.pnlCharEdit.refreshCharInfo(GDCharEditPane.this.info);
            }
            GDMsgLogger.showLog(GDCharEditPane.this, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERRORS"));
        }
    }

    private class CharSelectActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            final int idx = GDCharEditPane.this.cbSelChar.getSelectedIndex();
            if (idx == -1) {
                return;
            }
            if (idx == 0) {
                GDCharEditPane.this.setChar(null);
                return;
            }
            int i = 1;
            for (final GDCharInfoList.GDCharFileInfo info : GDCharInfoList.gdCharFileInfos) {
                if (i == idx) {
                    if (info.gdChar == null) {
                        (info.gdChar = new GDChar(info.charFile)).read();
                    }
                    if (info.gdChar.hasErrors()) {
                        info.gdChar = null;
                    }
                    if (info.gdChar != null) {
                        info.gdChar.getMasteryInfo();
                    }
                    GDCharEditPane.this.setChar(info);
                    break;
                }
                ++i;
            }
            GDMsgLogger.showLog(GDCharEditPane.this, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERRORS"));
        }
    }

    private class FileSaveActionListener implements ActionListener {
        @Override
        public void actionPerformed(final ActionEvent ev) {
            if (GDCharEditPane.this.info == null) {
                return;
            }
            if (GDCharEditPane.this.info.charFile == null) {
                return;
            }
            if (GDCharEditPane.this.info.gdChar == null) {
                return;
            }
            if (GDCharEditPane.this.frame.isCloudSaveDir() && GDStashFrame.isGrimDawnRunning()) {
                GDMsgLogger.addInfo(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_CLOUD_SAVE"));
                GDMsgLogger.addInfo(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_CLOSE"));
                GDMsgLogger.showLog(GDCharEditPane.this.frame, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_RUNNING"), GDLog.MessageType.Info, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "INFO_GD_RUNNING"));
                return;
            }
            final String origName = GDCharEditPane.this.info.gdChar.getCharName();
            final String newName = GDCharEditPane.this.tabEdit.getCharName();
            if (origName != null && newName != null && !origName.equals(newName)) {
                try {
                    final File fDirOrig = GDCharEditPane.this.info.charFile.getParentFile();
                    final String dirOrig = fDirOrig.getCanonicalPath();
                    final int pos = dirOrig.lastIndexOf(GDConstants.FILE_SEPARATOR);
                    if (pos != -1) {
                        final String name = dirOrig.substring(pos + 2);
                        String dirNew = dirOrig.substring(0, pos + 1);
                        dirNew = dirNew + "_" + newName;
                        final File fDirNew = new File(dirNew);
                        if (fDirNew.exists()) {
                            final GDLogoDialog dialog = new GDLogoDialog(GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERR_CHAR_EXISTS"), 4, GDCharEditPane.this.frame);
                            dialog.setVisible(true);
                            return;
                        }
                    }
                } catch (IOException ex) {
                    GDMsgLogger.addError(ex);
                }
            }
            GDCharEditPane.this.updateChar();
            boolean success = false;
            try {
                GDCharEditPane.this.info.gdChar.write();
                final String charName = GDCharEditPane.this.info.gdChar.getCharName();
                if (charName != null && !charName.isEmpty()) {
                    final File fDirOrig2 = GDCharEditPane.this.info.charFile.getParentFile();
                    final String dirOrig2 = fDirOrig2.getCanonicalPath();
                    final int pos2 = dirOrig2.lastIndexOf(GDConstants.FILE_SEPARATOR);
                    if (pos2 != -1) {
                        final String name2 = dirOrig2.substring(pos2 + 2);
                        String dirNew2 = dirOrig2.substring(0, pos2 + 1);
                        if (!name2.equals(charName)) {
                            dirNew2 = dirNew2 + "_" + charName;
                            final File fDirNew2 = new File(dirNew2);
                            fDirOrig2.renameTo(fDirNew2);
                            GDStashFrame.renameCharDir(fDirOrig2, fDirNew2, GDCharEditPane.this.frame);
                        }
                    }
                }
                success = true;
            } catch (IOException ex2) {
                GDMsgLogger.addError(ex2);
            }
            GDMsgLogger.showLog(GDCharEditPane.this.frame, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "SUCC_CHAR_SAVE"), GDLog.MessageType.Success, GDMsgFormatter.getString(GDMsgFormatter.rbUI, "ERR_CHAR_SAVE"), true);
        }
    }
}
